﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpShare {
    public interface ICastable<TType> where TType : class {
        /// <summary>
        /// Attempts to cast the object to the type.
        /// </summary>
        /// <returns>An object of TType, or null if the object can't be casted.</returns>
        TType TryCast();
    }

    public static class Castable {
        public static bool Is<TType>(this ICastable<TType> castable) where TType : class {
            return (castable.As<TType>() != null);
        }
        public static TType As<TType>(this ICastable<TType> castable) where TType : class {
            if (castable == null) {
                return null;
            }

            TType casted = castable.TryCast();

            return casted;
        }

        public static TType Cast<TType>(this ICastable<TType> castable) where TType : class {
            if (castable == null) throw new ArgumentNullException("castable");

            TType casted = castable.As<TType>();

            if (casted == null) {
                throw new InvalidCastException();
            }

            return casted;
        }
    }
}
